package cn.gcjxsc.messaging.sink;

import cn.gcjxsc.common.consts.RedPackType;
import cn.gcjxsc.common.data.notify.redpack.RedPackResultData;
import cn.gcjxsc.common.util.validator.BindResult;
import cn.gcjxsc.consts.merchant.MerchantAccountType;
import cn.gcjxsc.entity.merchant.Merchant;
import cn.gcjxsc.entity.merchant.MerchantAccount;
import cn.gcjxsc.entity.merchant.redpack.RedPackRecord;
import cn.gcjxsc.service.integral.MemberWxRedPackService;
import cn.gcjxsc.service.merchant.MerchantAccountService;
import cn.gcjxsc.service.merchant.MerchantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.SubscribableChannel;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.Set;

/**
 * @author pumbaa
 * @since 1.0
 */
@EnableBinding(RedPackResultSink.Sink.class)
public class RedPackResultSink {
    private Logger logger = LoggerFactory.getLogger(RedPackResultSink.class);
    @Autowired
    private MemberWxRedPackService redPackService;
    @Autowired
    private MerchantAccountService accountService;
    @Autowired
    private MerchantService merchantService;

    /**
     * 微信红包发送结果反馈
     * @param data
     */
    @StreamListener(Sink.QUEUE_NAME)
    public void process(RedPackResultData data) {
        //检查数据
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<RedPackResultData>> validate = validator.validate(data);
        if (validate.size() > 0) {
            logger.error("数据不正确.{}", validate.iterator().next().getMessage());
            return;
        }
        String sn = data.getSn();
        Integer type = data.getType();
        String status = data.getStatus();

        RedPackRecord record = redPackService.findBySnAndType(sn, type);
        if (null == record) {
            logger.error("商户红包流水记录不存在.{}, {}", sn, type);
            return;
        }
        if (status.equals("00")) {
            try {
                redPackService.processRedPackSuccess(record, data);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("处理红包反馈信息出错.状态:{},记录id:{},交易号:{}", status, record.getId(), data.getTradeNo());
            }
        }
        else {
            Integer merchantId = record.getOwnerId();
            Merchant merchant = merchantService.findById(merchantId);
            MerchantAccount account = accountService.findByMerchantIdAndType(merchant, MerchantAccountType.WX_CASH.getType());

            RedPackRecord backRecord = new RedPackRecord();
            BeanUtils.copyProperties(record, backRecord);

            backRecord.setAmount(BigDecimal.valueOf(data.getAmount()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_UP));
            backRecord.setTradeNo(data.getTradeNo());
            backRecord.setDoneTime(System.currentTimeMillis()/1000);
            if (data.getType() == RedPackType.BUY.getType()) {
                backRecord.setType(RedPackType.BUY_BACK.getType());
            }
            else if (data.getType() == RedPackType.SHARE.getType()) {
                backRecord.setType(RedPackType.SHARE_BACK.getType());
            }
            try {
                redPackService.processRedPackFail(account, record, backRecord);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("处理红包反馈信息出错.状态:{},记录id:{}", status, record.getId());
            }
        }

    }

    public interface Sink {
        String QUEUE_NAME = "rw_wx_redpack_result_input";

        @Input(QUEUE_NAME)
        SubscribableChannel input();
    }
}
